package com.serkol.ams.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.serkol.ams.bean.MyPage;
import com.serkol.ams.bean.MyPageOld;
import com.serkol.ams.entity.Agent;
import com.serkol.ams.entity.LoginLog;
import com.serkol.ams.mapper.AgentMapper;
import com.serkol.ams.modal.SqlFeildModal;
import com.serkol.ams.service.AgentService;
import com.serkol.ams.service.UsersService;
import com.serkol.constant.AuthConstant;
import com.serkol.handler.MyLambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author pingan
 * @description 针对表【agent】的数据库操作Service实现
 * @createDate 2022-09-20 11:45:23
 */
@Service
public class AgentServiceImpl extends ServiceImpl<AgentMapper, Agent>
        implements AgentService {
    @Autowired
    private UsersService userService;
    @Override
    public Map<String, Object> findByMapId(Long agentId) {
/*        QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
        queryWrapper.select(SqlFeildModal.getAgentFeild());
        queryWrapper.lambda().eq(Agent::getId, agentId);*/
        MyLambdaQueryWrapper<Agent> queryWrapper = new MyLambdaQueryWrapper<>();
        //  queryWrapper.select(SqlFeildModal.getUsersFeild());
        queryWrapper.select(Agent::getId, Agent::getLevel, Agent::getName, Agent::getPrice, Agent::getState,Agent::getNameUg);
        queryWrapper.picture(Agent::getImageId).as("url");
        queryWrapper.eq(Agent::getId, agentId);

        return this.getMap(queryWrapper);
    }

    @Override
    public MyPage<Map<String, Object>> findByList(int pageSize, int current) {
        MyLambdaQueryWrapper<Agent> queryWrapper = new MyLambdaQueryWrapper<>();
        //  queryWrapper.select(SqlFeildModal.getUsersFeild());
        queryWrapper.select(Agent::getId, Agent::getLevel,  Agent::getPrice, Agent::getState,Agent::getNameUg);
        queryWrapper.picture(Agent::getImageId).as("url").langName(Agent::getName, Agent::getNameUg).as("name");
        queryWrapper.orderByAsc(Agent::getLevel);
        Page<Map<String, Object>> page = new Page<>(current, pageSize);
        Page<Map<String, Object>> mapPage = this.baseMapper.selectMapsPage(page, queryWrapper);
        return MyPage.parsePage(mapPage);
    }

    @Override
    public long getOrdinary(int state) {
        QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("ID");
        queryWrapper.lambda().eq(Agent::getState, state);
        queryWrapper.last("LIMIT 1");
        Long obj = this.getObj(queryWrapper, (o) -> Long.parseLong(o.toString()));

        return obj;
    }

    @Override
    public List<Map<String, Object>> findByMiniList(long userId) {
        List<Map<String, Object>> maps=  this.baseMapper.findByMiniList(userId);
        return maps;
    }

    @Override
    public List<Map<String, Object>> findByPerList(long userId) {
        List<Long> findChildrens =null;
        if(userId>0){
            findChildrens=userService.getFindChildrens(userId);
        }else {
             LoginLog loginLog = AuthConstant.getLoginLog();
            findChildrens=userService.getFindChildrens(loginLog.getUserId());
        }
        findChildrens.add(0L);
         List<String> collect = findChildrens.stream().map(o -> {
            return String.valueOf(o);
        }).collect(Collectors.toList());
         String join = String.join(",", collect);
        MyLambdaQueryWrapper<Agent> queryWrapper=new MyLambdaQueryWrapper<>();
        queryWrapper.langName(Agent::getName,Agent::getNameUg).as("name").eq(Agent::getState,1)
                        .select(Agent::getId,Agent::getLevel)
.select("(SELECT IFNULL(SUM(PAYMENT_AMOUNT),0) FROM  order_master as torder_master WHERE IS_PAY=1 AND STATUS=2 AND USER_ID in((SELECT ID FROM  users as tusers WHERE AGENT_ID=x.ID AND ID IN("+join+"))) AND NOW()>=DATE_ADD(date(now()),INTERVAL -6 YEAR_MONTH) )").as("halfYear")
.select("(SELECT IFNULL(SUM(PAYMENT_AMOUNT),0) FROM  order_master as torder_master WHERE IS_PAY=1 AND STATUS=2 AND USER_ID in((SELECT ID FROM  users as tusers WHERE AGENT_ID=x.ID AND ID IN("+join+")))  )").as("fullYear");

        return this.listMaps(queryWrapper);
    }

    @Override
    public Agent getByAgent(BigDecimal paymentAmount, Long agentId) {
        LambdaQueryWrapper<Agent> queryWrapper=new LambdaQueryWrapper<>();
queryWrapper.orderByDesc(Agent::getPrice).last("LIMIT 1");
queryWrapper.le(Agent::getPrice,paymentAmount).ge(Agent::getId,agentId).or().eq(Agent::getId,agentId);
         Agent one = getOne(queryWrapper);
        return one;
    }
    @Cacheable(value = "stastica", key = "'homeAgentChartStastic'")
    @Override
    public List<Map<String, Object>> homeAgentChartStastic() {
        //SELECT NAME,(SELECT COUNT(*) FROM users WHERE AGENT_ID=x.ID) as count FROM agent as x where x.STATE=1
        MyLambdaQueryWrapper<Agent> queryWrapper=new MyLambdaQueryWrapper<>();
        queryWrapper.select(Agent::getName).eq(Agent::getState,1)
                .select("(SELECT COUNT(*) FROM users as tusers WHERE tusers.AGENT_ID=x.ID)").as("count");
        return this.listMaps(queryWrapper);

    }
}




